import React, { useCallback, useEffect, useRef, useState } from 'react';
import api from '../../utils/api';
import { Upload, Table, Button, Card, message, Space, Typography, Tooltip } from 'antd';
import { UploadOutlined, DeleteOutlined, FileOutlined, DownloadOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';

const { Title } = Typography;

// 修改组件名称避免与浏览器 File 冲突
const FileManager: React.FC = () => {
    const [files, setFiles] = useState<any[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [uploading, setUploading] = useState<boolean>(false);
    const fetchInProgress = useRef(false);
    // 文件列表
    const fetchFiles = useCallback(async () => {
        // 如果已经在获取中，则直接返回
        if (fetchInProgress.current) return;
        fetchInProgress.current = true;
        setLoading(true);
        try {
            const response = await api.get('/files');
            console.log('获取到文件列表:', response.data);
            // 确保数据是数组
            if (Array.isArray(response.data)) {
                setFiles(response.data);
            } else {
                console.error('文件列表数据不是数组:', response.data);
                setFiles([]);
            }
        } catch (error) {
            console.error('获取文件列表失败', error);
            message.error('获取文件列表失败');
        } finally {
            setLoading(false);
            fetchInProgress.current = false;
        }
    }, []);

    // 仅在组件挂载时触发一次
    useEffect(() => {
        console.log('文件管理器组件挂载，获取文件列表');
        fetchFiles();
        // 清理函数，确保组件卸载时停止请求
        return () => {
            fetchInProgress.current = true; // 阻止任何正在进行的请求
        };
    }, [fetchFiles]);



    const handleUpload: UploadProps['customRequest'] = async (options) => {
        const { file, onSuccess, onError, onProgress } = options;

        setUploading(true);
        const formData = new FormData();
        formData.append('file', file as File);

        try {
            onProgress && onProgress({ percent: 50 });

            const response = await api.post('/files/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });

            message.success(`${(file as File).name} 上传成功`);
            onSuccess && onSuccess(response.data);

            console.log('上传成功，刷新文件列表');
            // 确保文件列表刷新
            setTimeout(() => fetchFiles(), 500); // 短暂延迟确保服务器处理完成
        } catch (error) {
            console.error('文件上传失败', error);
            message.error(`${(file as File).name} 上传失败`);
            onError && onError(new Error('上传失败'));
        } finally {
            setUploading(false);
        }
    };

    const handleDelete = async (fileId: number) => {
        try {
            await api.delete(`/files/${fileId}`);
            message.success('文件删除成功');
            fetchFiles(); // 重新加载文件列表
        } catch (error: any) {
            console.error('删除文件失败', error);
            // 处理特定错误消息
            if (error.response?.data?.message) {
                message.error(error.response.data.message);
            } else {
                message.error('删除文件失败');
            }
        }
    };

    const handleDownload = async (fileId: number, filename: string) => {
        try {
            // 使用fetch而不是api，以便能够获取blob
            const response = await fetch(`/download/${fileId}`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`, // 如果使用token认证
                },
            });
            if (!response.ok) {
                throw new Error('下载失败');
            }
            // 从响应创建一个blob URL
            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);

            // 创建隐藏的下载链接并点击
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            // 清理
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        } catch (error) {
            console.error('文件下载失败', error);
            message.error('文件下载失败');
        }
    };

    const columns = [
        {
            title: '文件名',
            dataIndex: 'filename',
            key: 'filename',
            render: (text: string) => (
                <Space>
                    <FileOutlined />
                    <span>{text}</span>
                </Space>
            ),
        },
        {
            title: '文件大小',
            dataIndex: 'file_size',
            key: 'file_size',
            render: (size: number) => {
                const kb = size / 1024;
                if (kb < 1024) {
                    return `${kb.toFixed(2)} KB`;
                } else {
                    const mb = kb / 1024;
                    return `${mb.toFixed(2)} MB`;
                }
            },
        },
        {
            title: '文件路径',
            dataIndex: 'file_path',
            key: 'file_path',
            render: (path: string) => path ? (
                <Tooltip title={path}>
                    <span>{path.split('/').pop() || path}</span>
                </Tooltip>
            ) : '-',
        },
        {
            title: '操作',
            key: 'action',
            render: (_: any, record: any) => (
                <Space size="middle">
                    <Tooltip title="下载">
                        <Button
                            type="text"
                            icon={<DownloadOutlined />}
                            onClick={() => handleDownload(record.id, record.filename)}
                        />
                    </Tooltip>
                    <Tooltip title="删除">
                        <Button
                            type="text"
                            danger
                            icon={<DeleteOutlined />}
                            onClick={() => handleDelete(record.id)}
                        />
                    </Tooltip>
                </Space>
            ),
        },
    ];

    return (
        <Card
            title={<Title level={4}>文件管理</Title>}
            extra={
                <Upload
                    customRequest={handleUpload}
                    showUploadList={false}
                >
                    <Button
                        type="primary"
                        icon={<UploadOutlined />}
                        loading={uploading}
                        disabled={uploading}
                    >
                        {uploading ? '上传中...' : '上传文件'}
                    </Button>
                </Upload>
            }
            style={{ width: '100%', marginBottom: 20 }}
        >
            <Table
                columns={columns}
                dataSource={files}
                rowKey="id"
                loading={loading}
                pagination={{ pageSize: 10 }}
                locale={{ emptyText: '暂无文件' }}
            />
        </Card>
    );
};

export default FileManager;